<template>
  <div>
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <select-confirm-batch
          placeholder="审核批次"
          @change="getData()"
          @clear="getData()"
          clearable
          v-model="params['apply_batch_no.eq']"
        ></select-confirm-batch>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="通过时间(开始)"
          end-placeholder="通过时间(截止)"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="项目状态"
          clearable
          number-key
          :options="enumConfirmStatus"
          v-model="params['is_confirm.eq']"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="exportExcel('存量-项目确认')">导出</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:button="scope">
        <el-button
          @click="handleSignAttach(scope.row)"
          type="text"
          v-if="+scope.row.is_confirm === 0 && scope.row.submit_person === userId"
        >
          盖章上传
        </el-button>
        <el-button @click="handleView(scope.row)" type="text" :loading="dowloading">
          确认表下载
        </el-button>
        <el-button @click="handleinlieView(scope.row)" type="text">在线预览</el-button>
        <el-button @click="handleAttach(scope.row)" type="text">查看</el-button>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <!-- <confirm-sign-attach-dialog :visible.sync="signAttachVisible"
                                :batch-data="signAttachBatchData"></confirm-sign-attach-dialog> -->

    <attach-upload-dialog
      :visible.sync="signAttachVisible"
      :attach-id="signAttachBatchNo"
      :before-upload="beforeUpload"
      attach-tag="项目确认表"
      title="盖章上传"
      @success="onUploadSuccess"
    ></attach-upload-dialog>

    <confirm-view-dialog
      :visible.sync="viewVisible"
      :batch-data="viewBatchData"
      :batch-no="viewBatchData.project_approval_batch_bank_id"
    ></confirm-view-dialog>

    <confirm-attach-dialog
      :visible.sync="attachVisible"
      :batch-data="attachBatchData"
    ></confirm-attach-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumConfirmStatus,
  enumConfirmStatusStyle,
  enumWarrantyStatus,
  enumWarrantyStyle,
} from '@/bank/views/limit/confirm/mixins'
import { lastPickerShortcuts } from '@/common/plugins/tools/date'
import { deleteOss } from '@/common/api/oss'

import SelectConfirmBatch from '@/bank/views/business/industry/history/confirm/SelectConfirmBatch'
import ConfirmViewDialog from '@/bank/views/business/industry/history/confirm/ConfirmViewDialog'
import ConfirmAttachDialog from '@/bank/views/business/industry/history/confirm/ConfirmAttachDialog'
// import ConfirmSignAttachDialog from '@/bank/views/limit/confirm/ConfirmSignAttachDialog'
import AttachUploadDialog from '@/bank/components/attach/UploadDialog'
import { downLoadPdf } from '@/credit/views/county/unionProvince/components/pdf'
import { getAddressNextValue } from '@/common/api/address'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
export default {
  components: {
    SelectConfirmBatch,
    ConfirmViewDialog,
    ConfirmAttachDialog,
    // ConfirmSignAttachDialog
    AttachUploadDialog,
  },
  props: {},
  data() {
    return {
      enumConfirmStatus,

      loading: false,
      params: {
        index: 1,
        size: 10,
        'apply_batch_no.eq': '',
        'is_confirm.eq': '',
        'channel_type.eq': 0,
        'is_rural_dev.eq': 1,
        'project_count_approval.gt': 0,
      },
      order: {
        approval_time: 'desc',
      },
      tableName: 'project_approval_batch_bank',
      serachTable: 'project_approval_batch_bank_view',
      tableColumns: [
        { attrs: { label: '审核批次', prop: 'apply_batch_no', align: 'center' } },
        { attrs: { label: '审核数量', prop: 'project_count', align: 'center' } },
        { attrs: { label: '审核总额(万元)', prop: 'project_funds', align: 'center' } },
        {
          attrs: { label: '审核机构', prop: 'person', align: 'center' },
          process: () => '省农担',
        },
        {
          attrs: { label: '通过时间', prop: 'approval_time', align: 'center' },
        },
        { attrs: { label: '通过数量', prop: 'project_count_approval', align: 'center' } },
        { attrs: { label: '通过金额(万元)', prop: 'project_funds_approval', align: 'center' } },
        { attrs: { label: '应收担保费(元)', prop: 'warranty_fee', align: 'center' } },
        {
          attrs: { label: '担保费收取', prop: 'warrantyStatus', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.warrantyStyle}` } }),
        },
        {
          attrs: { label: '批次状态', prop: 'confirmStatusLabel', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.confirmStatusStyle}` } }),
        },
        { attrs: { label: '提交机构', prop: 'submit_bank_name', align: 'center' } },
        {
          attrs: { label: '确认时间', prop: 'confirm_time', align: 'center' },
          process: v => v || '-',
        },
        {
          attrs: { label: '操作', align: 'center', minWidth: '120px' },
          slot: 'button',
          // operations: [
          //   {
          //     name: '盖章上传',
          //     event: this.handleSignAttach,
          //     ifRender: row => row.is_confirm === 0,
          //   },
          //   { name: '附件', event: this.handleView, loading: this.dowloading },
          //   { name: '查看', event: this.handleAttach },
          // ],
        },
      ],
      tableData: [],
      tableCount: 0,

      // 提交时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },

      // 查看
      viewVisible: false,
      viewBatchData: {},

      // 附件上传
      attachVisible: false,
      attachBatchData: {},

      // 盖章上传
      signAttachVisible: false,
      signAttachBatchData: {},
      signAttachBatchNo: '',
      dowloading: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'userId', 'user', 'org']),
    productId() {
      return this.$route.query.id
    },
    isSubmit() {
      return this.user.scopes.includes('indoneBI')
    },
    isSYSTEM() {
      // 系统后台查所有
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {},
  created() {
    if (!this.isSYSTEM) {
      const { queryAddressCode, clientOrgClassType } = this.user
      if (this.isSubmit) {
        this.params.orWhereAndTemplate = 2
        this.params['orWhereAnd.submit_client_id.eq'] = this.clientId
        this.params['orWhereAnd.bank_type.in'] = clientOrgClassType
        this.params['orWhereAnd.submit_bank_address_code.gt'] = queryAddressCode
        this.params['orWhereAnd.submit_bank_address_code.lt'] =
          getAddressNextValue(queryAddressCode)
        this.params['orWhereAnd.bank_type.eq'] = clientOrgClassType
      } else {
        this.params['submit_person.eq'] = this.userId
      }
    }
    this.getData()
  },
  mounted() {},
  methods: {
    async exportExcel(filename) {
      const exportTable = this.tableColumns.filter(item => !item.operations && !item.hidden)
      const header = {}

      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}3`] = { font: { bold: true } }
        // headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })

      let data = []

      this.exportLoading = true
      const { index, size, ...params } = this.params
      const res = await this.$api.getData(this.$serviceName, this.serachTable, params, this.order)
      data = (res.data || []).map((item, index) => {
        return {
          index: index + 1,
          ...this.dataAdapter(item),
        }
      })

      const title1 = {
        index: '黔农十二贷',
      }
      excelJsonExport({
        columns,
        data: [title1, title1, title1, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:AE3'],
        cols: [{ wch: 6 }],
        cellStyles: {
          A1: {
            alignment: { horizontal: 'left' },
            font: { bold: true, sz: 24 },
          },
          A2: { alignment: { horizontal: 'left' }, font: { bold: true } },
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.serachTable, this.params, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = (data.data || []).map(this.dataAdapter)
          this.tableCount = data.totalCount || 0
        })
        .finally(() => {
          this.loading = false
        })
    },

    dataAdapter(item) {
      item.person = '省农担'
      item.is_confirm = +(item.is_confirm || 0)
      item.confirmStatusLabel = enumConfirmStatus[item.is_confirm]
      item.confirmStatusStyle = enumConfirmStatusStyle[item.is_confirm]
      item.warrantyStatus = enumWarrantyStatus[item.warranty_fee_confirm]
      item.warrantyStyle = enumWarrantyStyle[item.warranty_fee_confirm]
      return item
    },

    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['approval_time.gte'] = start
        this.params['approval_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['approval_time.gte'] = ''
        this.params['approval_time.lte'] = ''
      }
      this.getData()
    },

    handleSignAttach(row = {}) {
      this.signAttachBatchData = row
      this.signAttachBatchNo = row.project_approval_batch_bank_id
      this.signAttachVisible = true
    },

    handleView(row = {}) {
      this.dowloading = true
      downLoadPdf(row.doc_id, '确认表').finally(() => {
        this.dowloading = false
      })
    },
    handleinlieView(row = {}) {
      if (+row.project_count < 1000) {
        this.viewBatchData = row
        this.viewVisible = true
        return
      }
      this.$utils
        .msgbox({
          message: '提示：批次项目过多，防止页面卡顿，请下载后本地预览',
        })
        .catch(() => {})
    },

    handleAttach(row = {}) {
      this.attachBatchData = row
      this.attachVisible = true
    },

    beforeUpload() {
      return new Promise((resolve, reject) => {
        this.$utils
          .msgbox({
            message: '确定盖章上传（上传后该审核批次将变成已确认）？',
            type: 'warning',
          })
          .then(() => {
            resolve(true)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    onUploadSuccess(res) {
      this.loading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.signAttachBatchNo, {
          is_confirm: 1,
        })
        .then(() => {
          this.$message.success('盖章上传成功！')
          this.getData()
          this.$store.dispatch('getTaskCountIndustry', { type: 0, id: this.productId })
        })
        .catch(err => {
          this.$message.error('盖章上传失败!')

          // 错误后，要删除附件信息和oss文件
          const { list = [] } = res || {}
          this.deleteAttachByBatchNo(list)

          throw new Error(err)
        })
        .finally(() => {
          this.loading = true
        })
    },

    deleteAttachByBatchNo(list) {
      this.$api
        .deleteDataBody(this.$serviceName, 'datum_customer_attachment', {
          customer_related_id: this.signAttachBatchNo,
        })
        .then(() => {
          deleteOss(list)
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
